package com.hanxiaozhang.threadbase1ndedition.no0interview;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 * 实现一个容器，提供两个方法，add，size
 * 写两个线程，线程1添加10个元素到容器中，线程2实现监控元素的个数，当个数到5个时，线程2给出提示并结束
 *
 * @author hanxinghua
 * @create 2021/11/14
 * @since 1.0.0
 */
public class No1 {

    private List lists = new ArrayList();

    public void add(Object o) {
        lists.add(o);
    }

    public int size() {
        return lists.size();
    }

    public static void main(String[] args) {
        No1 no1 = new No1();
        CountDownLatch t1Latch = new CountDownLatch(1);
        CountDownLatch t2Latch = new CountDownLatch(1);

        new Thread(() -> {
            System.out.println("t1 开始");
            for (int i = 0; i < 10; i++) {
                no1.add(new Object());
                System.out.println("add " + i);
                if (no1.size() == 5) {
                    t1Latch.countDown();
                    try {
                        t2Latch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
//                try {
//                    TimeUnit.SECONDS.sleep(1);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }
            System.out.println("t1 结束");
        }, "t1").start();

        new Thread(() -> {
            if (no1.size() != 5) {
                try {
                    t1Latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("t2 结束");
            t2Latch.countDown();
        }, "t2").start();

    }
}
